package net.htjs.juc.chapter06.atomicreference;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

@Slf4j
public class AtomicStampedAba {

    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);

    public static void main(String[] args) throws InterruptedException {
        log.info("main start");
        //获取值A
        //这个共享变量是否被其他线程修改过
        String prev = ref.getReference();
        //获取版本号
        int stamp = ref.getStamp();
        log.info("stamped:{}", stamp);
        other();
        Thread.sleep(1000);
        log.info("stamped:{}", stamp);
        log.info("change A -> C {}", ref.compareAndSet(prev, "C", stamp, stamp + 1));
    }

    private static void other() throws InterruptedException {
        new Thread(() -> {
            log.info("thread1 start");
            int stamp =  ref.getStamp();
            log.info("stamped:{}", stamp);
            log.info("change A -> B {}", ref.compareAndSet(ref.getReference(), "B", stamp, stamp + 1));
        }).start();
        Thread.sleep(500);
        new Thread(() -> {
            log.info("thread2 start");
            int stamp =  ref.getStamp();
            log.info("stamped:{}", stamp);
            log.info("change B -> A {}", ref.compareAndSet(ref.getReference(), "A", stamp, stamp + 1));
        }).start();
    }


}
